package com.shuyi.scaffold.config.redis;

import cn.hutool.core.text.CharSequenceUtil;
import lombok.AllArgsConstructor;
import org.redisson.api.NameMapper;
import org.redisson.config.Config;
import org.redisson.spring.starter.RedissonAutoConfigurationCustomizer;

/**
 * @author yangyidian
 * @date 2022/08/22
 **/
@AllArgsConstructor
public class CustomRedissonAutoConfigurationCustomizer implements RedissonAutoConfigurationCustomizer {
    private final String keyPrefix;

    @Override
    public void customize(Config cfg) {
        NameMapper nameMapper = new NameMapper() {
            @Override
            public String map(String name) {
                return keyPrefix + ":" + name;
            }

            @Override
            public String unmap(String name) {
                return CharSequenceUtil.subAfter(name, keyPrefix + ":", false);
            }
        };
        if (cfg.isClusterConfig()) {
            cfg.useClusterServers().setNameMapper(nameMapper);
        } else if (cfg.isSentinelConfig()) {
            cfg.useSentinelServers().setNameMapper(nameMapper);
        } else {
            cfg.useSingleServer().setNameMapper(nameMapper);
        }
    }
}
